package com.ensentec.Lib;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by ztlchina on 17-7-29.
 */

public class CardReader {
    private static CardReader ourInstance;

    public static CardReader getInstance() {
        if (null == ourInstance)
        {
            ourInstance = new CardReader();
            ourInstance.onCreate();
        }
        return ourInstance;
    }

    private String TAG = CardReader.class.getSimpleName();
    private SerialPort mSerialPort;
    private OutputStream mOutputStream;
    private InputStream mInputStream;
    private ReadThread mReadThread;
    private String path = "/dev/ttySAC3";
    private int baudrate = 19200;
    private int stop = 1;
    private int bits = 8;
    private byte even = 0x02;   //偶校验
    private int block = 1;

    private OnGetCardNO onGetCardNO = null;
    private volatile boolean isStop = false;

    public interface OnGetCardNO {
        public void onGetCardNO(byte[] cardno);
    }

    public void setGetCardNOListener(
            OnGetCardNO getScaleValue) {
        onGetCardNO = getScaleValue;
    }
    /**
     * 初始化串口信息
     */
    public void onCreate() {
        try {
            mSerialPort = new SerialPort(new File(path), baudrate, bits, even, stop, block);
            mOutputStream = mSerialPort.getOutputStream();
            mInputStream = mSerialPort.getInputStream();

            mReadThread = new ReadThread();

            isStop = false;
            mReadThread.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class ReadThread extends Thread {

        @Override
        public void run() {
            super.run();
            while (!isStop && !isInterrupted()) {
                int size;
                try {
                    if (mInputStream == null) {
                        return;
                    }

                    Thread.sleep(300);      //sleep 100ms

                    byte[] buffer = new byte[128];
                    size = mInputStream.read(buffer);
                    if (size > 0) {

                        //Todo:解析数据;
                        if (null != onGetCardNO) {
                            onGetCardNO.onGetCardNO(buffer);
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                }
            }
        }
    }

    /**
     * 关闭串口
     */
    public void closeSerialPort() {
        isStop = true;
        if (mReadThread != null) {
            mReadThread.interrupt();
        }
        if (mSerialPort != null) {
            mSerialPort.close();
        }
    }
}
